package com.jingxi.service;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.jingxi.common.pojo.EasyUIDataGridResult;
import com.jingxi.common.pojo.JingXiResult;
import com.jingxi.common.util.HttpClientUtil;
import com.jingxi.mapper.TbContentMapper;
import com.jingxi.model.TbContent;
import com.jingxi.model.TbContentExample;

@Service
public class ContentServiceImpl implements ContentService {

	@Value("${REST_BASE_URL}")
	private String REST_BASE_URL;
	
	@Autowired
	private TbContentMapper tbContentMapper;

	@Override
	public EasyUIDataGridResult getContentWithCatId(long categoryId, int page, int rows) {
		System.out.println(categoryId + "aaa" + page + "vvv" + rows);
		TbContentExample example = new TbContentExample();
		// Criteria criteria = example.createCriteria();
		// criteria.andCategoryIdEqualTo(categoryId);
		// 杩樻槸瑙ｅ喅涓嶄簡閭ｄ釜寮傚父銆傘�傚厛杩欐牱鍚э紝鍏堟煡鍑烘潵鍐嶈繃婊ゃ�傘��
		List<TbContent> list = tbContentMapper.selectByExampleWithBLOBs(example);
		List<TbContent> listReal = new LinkedList<>();
		for (TbContent tbContent : list) {
			if (tbContent.getCategoryId() == categoryId)
				listReal.add(tbContent);
		}
		// 鍒嗛〉澶勭悊
		PageHelper.startPage(page, rows);
		// 鍒涘缓涓�涓繑鍥炲�煎璞�
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		result.setRows(listReal);
		result.setTotal(list.size());
		return result;
	}

	/**
	 * 鍒涘缓鏂扮殑Content
	 */
	@Override
	public JingXiResult saveContent(TbContent tbContent) {
		Date date = new Date();
		tbContent.setCreated(date);
		tbContent.setUpdated(date);
		tbContentMapper.insert(tbContent);
		// 娣诲姞缂撳瓨鍚屾閫昏緫
		try {
			HttpClientUtil.doGet(REST_BASE_URL + "/cache/sync/content/" + tbContent.getCategoryId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JingXiResult.ok();
	}

	/**
	 * 淇敼Content
	 */
	@Override
	public JingXiResult editContent(TbContent tbContent) {
		Date date = new Date();
		tbContent.setUpdated(date);
		tbContentMapper.updateByPrimaryKeySelective(tbContent);
		return JingXiResult.ok();
	}

	/**
	 * 鍒犻櫎Content
	 */
	@Override
	public JingXiResult deleteContent(long[] ids) {
		for (long id : ids) {
			tbContentMapper.deleteByPrimaryKey(id);
		}
		return JingXiResult.ok();
	}

}
